<template>
  <div class="register-container">
    <!-- 顶部返回和标题 -->
    <van-nav-bar 
      left-arrow 
      title="注册账号" 
      @click-left="handleGoBack"
      :border="false"
    />
    
    <!-- 应用标识 -->
    <div class="title-group">
      <van-icon name="gold-coin-o" class="icon" />
      <span class="title">欢迎注册</span>
    </div>

    <!-- 注册表单 -->
    <van-form @submit="handleRegister">
      <van-cell-group inset>
        <!-- 用户名 -->
        <van-field
          autocomplete="current-username"
          v-model="registerForm.username"
          label="用户名"
          placeholder="请输入用户名"
          :rules="[
            { required: true, message: '请填写用户名' },
            { pattern: /^.{2,10}$/, message: '用户名在2到10个字符之间' },
          ]"
        />
        <!-- 用户昵称 -->
        <van-field
          autocomplete="name"
          v-model="registerForm.nickname"
          label="用户昵称"
          placeholder="请输入用户昵称"
          :rules="[
            { required: true, message: '请填写用户昵称' },
            { pattern: /^.{2,10}$/, message: '用户昵称在2到10个字符之间' },
          ]"
        />
        <!-- 手机号 -->
        <van-field
          autocomplete="tel"
          v-model="registerForm.mobile"
          type="tel"
          label="手机号"
          placeholder="请输入手机号"
          :rules="[
            { required: true, message: '请输入手机号' },
            { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确' },
          ]"
        />
        <!-- 密码 -->
        <van-field
          autocomplete="current-password"
          v-model="registerForm.password"
          type="password"
          label="密码"
          placeholder="请输入密码"
          :rules="[
            { required: true, message: '请输入密码' },
            {
              pattern: /^[a-zA-Z0-9]{6,}$/,
              message: '密码至少6位，包含字母和数字',
            },
          ]"
        />
        <!-- 确认密码 -->
        <van-field
          autocomplete="new-password"
          v-model="registerForm.confirmPassword"
          type="password"
          label="确认密码"
          placeholder="请再次输入密码"
          :rules="[
            { required: true, message: '请再次输入密码' },
            {
              validator: (val) => val === registerForm.password,
              message: '两次输入的密码不一致',
            },
          ]"
        />
      </van-cell-group>

      <!-- 上传头像（移到协议前面） -->
      <div class="upload-avatar">
        <p class="upload-tip">上传头像（可选）</p>
        <van-uploader
          v-model="avatarFile"
          :after-read="handleAvatarUpload"
          :max-count="1"
          :preview-size="80"
          round
          :before-read="beforeAvatarRead"
        >
          <van-button
            v-if="!avatarFile || avatarFile.length === 0"
            icon="plus"
            type="primary"
            round
            plain
          >
            上传头像
          </van-button>
          <div v-else class="avatar-preview">
            <van-image
              round
              :src="avatarFile[0].content"
              width="80px"
              height="80px"
              fit="cover"
              @click="handleAvatarPreview"
            />
            <van-icon
              name="close"
              class="avatar-delete"
              @click.stop="handleAvatarDelete"
            />
          </div>
        </van-uploader>
      </div>

      <!-- 协议勾选 -->
      <div class="protocol-section">
        <van-checkbox
          v-model="agreeProtocol"
          shape="round"
          class="protocol-checkbox"
          checked-color="#ffcc00"
        >
          已阅读并同意《<a href="javascript:;" class="protocol-link">用户协议</a
          >》和《<a href="javascript:;" class="protocol-link">隐私协议</a>》
        </van-checkbox>
      </div>

      <!-- 注册按钮 -->
      <div class="btn-style">
        <van-button
          round
          block
          color="#ffcc00"
          text-color="#000"
          native-type="submit"
          :disabled="!agreeProtocol || isUploading"
        >
          <template v-if="isUploading">上传中...</template>
          <template v-else>立即注册</template>
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<script setup>
import { ref } from "vue";
import { useRouter } from "vue-router";
import { ImagePreview, showSuccessToast, showToast } from "vant";
// 导入注册接口
import { register, uploadImageApi } from "@/api";

const registerForm = ref({
  username: "",
  nickname: "",
  mobile: "",
  password: "",
  confirmPassword: "",
});
const agreeProtocol = ref(false);
const router = useRouter();
const avatarFile = ref([]); // 存储头像文件
const avatarUrl = ref(""); // 存储上传后的头像URL
const isUploading = ref(false); // 上传状态控制

// 注册处理
const handleRegister = async () => {
  if (!agreeProtocol.value) {
    showToast("请同意用户协议和隐私协议");
    return;
  }

  // 若有头像且未上传，先完成上传
  if (avatarFile.value.length > 0 && !avatarUrl.value) {
    isUploading.value = true;
    try {
      await uploadAvatar();
    } catch (e) {
      isUploading.value = false;
      return; // 上传失败终止注册
    }
  }

  // 准备注册数据
  const registerData = {
    username: registerForm.value.username,
    nickname: registerForm.value.nickname,
    mobile: registerForm.value.mobile,
    password: registerForm.value.password,
    avatar: avatarUrl.value, // 携带头像URL
  };

  try {
    const res = await register(registerData);
    showSuccessToast({
      message: "注册成功",
      duration: 1500,
    });

    // 延迟跳转到登录页
    setTimeout(() => {
      router.push({ name: "login" });
    }, 500);
  } catch (e) {
    console.error("注册失败:", e);
    const errorMessage = e.response?.data?.message || e.message || "系统异常";
    showToast("注册失败: " + errorMessage);
  } finally {
    isUploading.value = false;
  }
};

// 头像上传前校验
const beforeAvatarRead = (file) => {
  // 校验图片类型
  const isImage = file.type.startsWith("image/");
  if (!isImage) {
    showToast("请选择图片文件");
    return false;
  }
  // 校验图片大小（5MB以内）
  const isLt5M = file.size / 1024 / 1024 < 5;
  if (!isLt5M) {
    showToast("图片大小不能超过5MB");
    return false;
  }
  return true;
};

// 上传头像到后端
const uploadAvatar = async () => {
  try {
    const file = avatarFile.value[0].file;
    const formData = new FormData();
    formData.append("image", file); // 与后端FileController字段匹配

    const res = await uploadImageApi(formData);
    console.log("头像上传完整响应:", res);

    // 提取头像URL（兼容不同返回结构）
    let url = null;
    if (res?.data?.url) {
      url = res.data.url;
    } else if (res?.url) {
      url = res.url;
    } else if (res?.data?.data?.url) {
      url = res.data.data.url;
    }

    if (url) {
      avatarUrl.value = url;
      showToast("头像上传成功");
    } else {
      console.error("无法从响应中提取URL:", res);
      throw new Error("未获取到有效头像地址");
    }
  } catch (e) {
    console.error("头像上传失败:", e);
    // 上传失败清空状态
    avatarFile.value = [];
    avatarUrl.value = "";
    const errorMessage = e.response?.data?.message || e.message || "上传失败";
    showToast(errorMessage);
    throw e; // 向上传递错误
  }
};

// 处理头像选择
const handleAvatarUpload = (file) => {
  console.log("头像文件已选择:", file);
  // 自动触发上传
  uploadAvatar().catch(() => {});
};

// 预览头像
const handleAvatarPreview = () => {
  if (avatarFile.value.length > 0) {
    ImagePreview([avatarFile.value[0].content]);
  }
};

// 删除头像
const handleAvatarDelete = () => {
  avatarFile.value = [];
  avatarUrl.value = "";
  showToast("已移除头像");
};

// 返回上一页
const handleGoBack = () => {
  router.back();
};
</script>

<style lang="scss" scoped>
.register-container {
  min-height: 100vh;
  padding: 0 0 30px;
  background: linear-gradient(135deg, #fff 0%, #f7f8fa 100%);
  animation: fadeIn 0.5s ease-out;

  // 导航栏样式
  :deep(.van-nav-bar) {
    background: transparent;
    
    .van-nav-bar__title {
      font-size: 18px;
      font-weight: 500;
      color: #333;
    }
  }

  .title-group {
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 30px 0 25px;
    animation: slideInLeft 0.6s ease-out;

    .icon {
      font-size: 28px;
      color: #000;
      background: linear-gradient(135deg, #ffcc00 0%, #ffd814 100%);
      border-radius: 8px;
      padding: 6px;
      margin-right: 12px;
      width: 32px;
      height: 32px;
      display: flex;
      align-items: center;
      justify-content: center;
      box-shadow: 0 2px 8px rgba(255, 204, 0, 0.3);
    }

    .title {
      font-size: 24px;
      font-weight: 500;
      color: #333;
      letter-spacing: 1px;
    }
  }

  // 表单区域动画
  :deep(.van-cell-group) {
    animation: slideInUp 0.6s ease-out;
    margin-bottom: 20px;
  }

  // 头像上传区域
  .upload-avatar {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin: 20px 0;
    padding: 20px 0;
    animation: slideInUp 0.7s ease-out;

    .upload-tip {
      font-size: 14px;
      color: #666;
      margin-bottom: 15px;
      font-weight: 500;
    }

    :deep(.van-uploader__wrapper) {
      display: flex;
      flex-direction: column;
      align-items: center;
    }

    :deep(.van-button) {
      border-color: #ffcc00;
      color: #ffcc00;
      font-size: 14px;
      
      &:active {
        background-color: rgba(255, 204, 0, 0.1);
      }
    }

    :deep(.van-image) {
      border-radius: 50%;
      cursor: pointer;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    }

    .avatar-preview {
      position: relative;
      animation: zoomIn 0.3s ease-out;
    }

    .avatar-delete {
      position: absolute;
      bottom: -2px;
      right: -2px;
      background-color: rgba(0, 0, 0, 0.6);
      color: white;
      border-radius: 50%;
      width: 24px;
      height: 24px;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 16px;
      cursor: pointer;
      transition: all 0.3s;

      &:active {
        background-color: rgba(0, 0, 0, 0.8);
        transform: scale(1.1);
      }
    }
  }

  // 协议区域
  .protocol-section {
    padding: 10px 16px;
    animation: slideInUp 0.75s ease-out;
  }

  .protocol-checkbox {
    font-size: 12px;

    :deep(.van-checkbox__icon--round) {
      border-radius: 50%;
    }

    :deep(.van-checkbox__label) {
      line-height: 1.6;
    }

    .protocol-link {
      color: #ffcc00;
      text-decoration: underline;
      font-weight: 500;
    }
  }

  // 按钮区域
  .btn-style {
    margin: 20px 16px 10px;
    animation: slideInUp 0.8s ease-out;

    :deep(.van-button) {
      height: 50px;
      font-size: 17px;
      font-weight: 600;
      box-shadow: 0 4px 12px rgba(255, 204, 0, 0.3);
      transition: all 0.3s;
      letter-spacing: 2px;

      &:active {
        transform: scale(0.98);
      }

      &:disabled {
        opacity: 0.5;
        box-shadow: none;
      }
    }
  }
}

/* 动画定义 */
@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

@keyframes slideInLeft {
  from {
    opacity: 0;
    transform: translateX(-20px);
  }
  to {
    opacity: 1;
    transform: translateX(0);
  }
}

@keyframes slideInUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes zoomIn {
  from {
    opacity: 0;
    transform: scale(0.8);
  }
  to {
    opacity: 1;
    transform: scale(1);
  }
}
</style>

